<?php

namespace app\api\controller;

use app\api\ApiBaseController;
use app\task\model\CategoryModel;
use app\task\model\OrderModel;
use app\task\model\TaskModel;
use think\Exception;
use think\facade\Db;

/**
 * 登录接口
 */
class Task extends ApiBaseController
{
    /**
     * 不需要验证登录的接口
     * @var bool
     */
    public $noNeedLoginAuth = ['categoryList', 'taskList', 'taskListInMap', 'taskDetail'];

    /**
     * 订单任务分类列表
     */
    public function categoryList()
    {
        $list = CategoryModel::where(['is_deleted'=>0, 'status'=>1])
            ->field('id,name,img')
            ->order('sort desc, id desc')
            ->select();
        $this->success('ok', $list);
    }

    /**
     * 订单任务列表
     */
    public function taskList()
    {
        $query = TaskModel::alias('t')->with(['category', 'transport'])
            ->where(['t.is_deleted'=>0, 't.status'=>1])
            ->join('task_transport tr', 't.id=tr.task_id', 'left')
            ->field('t.id,t.name,t.exec_at,t.place,t.money,t.category_id')
            ->where('t.task_status', TaskModel::TASK_STATUS__PENDING_ACCEPTANCE)
            ->whereTime('t.exec_at', '>', date('Y-m-d H:i:s'));
        // 筛选项
        $category_id = $this->request->post('category_id', 0);
        $time_order = $this->request->post('time_order', 'desc');
        $price_order = $this->request->post('price_order', '');
        $transport_scene = $this->request->post('transport_scene', '');
        if (!empty($category_id)) $query->where('t.category_id', $category_id);
        if (!empty($transport_scene)) $query->where('tr.scene', $transport_scene);
        $order_arr = [];
        if (in_array($time_order, ['desc', 'asc'])) $order_arr[] = 't.exec_at '.$time_order;
        if (in_array($price_order, ['desc', 'asc'])) $order_arr[] = 't.money '.$price_order;
        $order_arr[] = 't.id desc';
        $query->order(join(',', $order_arr));
        $list = get_list($query);
        // 数据清洗
        foreach ($list['list'] as &$vo){
            $vo['exec_at'] = date('Y-m-d H:i', strtotime($vo['exec_at']));
            $vo['category'] = array_keep($vo['category'], ['id', 'name', 'img']);
            $vo['transport_type'] = $vo['transport']['type'] ?? '';
            $vo['transport_distance'] = $vo['transport']['distance'] ?? '';
            $vo['transport_scene'] = $vo['transport']['scene'] ?? '';
            $vo['weight'] = $vo['transport']['weight'] ?? '';
            $vo['money'] = get_task_pilot_money($vo['money']);
        }
        $this->success('ok', $list);
    }

    /**
     * 订单任务详情
     */
    public function taskDetail(){
        $id = $this->request->post('id', 0);
        $task = TaskModel::where(['is_deleted'=>0, 'status'=>1])->with(['category', 'transport'])
            ->field('id,name,exec_at,place,money,category_id,desc,require,lat,lng')
            ->where('id', $id)
            ->find();
        if (empty($task)) $this->error('订单任务不存在');
        $task = $task->toArray();
        $task['category'] = array_keep($task['category'], ['id', 'name', 'img']);
        $task['exec_at'] = date('Y-m-d H:i', strtotime($task['exec_at']));
        $task['money'] = get_task_pilot_money($task['money']);
        // 添加货运信息
        if($task['category_id'] == 1){
            $transport = $task['transport'];
            $task['start_at'] = date('Y-m-d H:i', strtotime($transport['start_at'] ?? ''));
            $task['end_at'] =  date('Y-m-d H:i', strtotime($transport['end_at'] ?? ''));
            $task['transport_type'] = $transport['type'] ?? '';
            $task['transport_scene'] = $transport['scene'] ?? '';
            $task['transport_distance'] = $transport['distance'] ?? '';
            $task['weight'] = $transport['weight'] ?? '';
            $task['province'] = $transport['province'] ?? '';
            $task['city'] = $transport['city'] ?? '';
            $task['area'] = $transport['area'] ?? '';
            $task['address'] = $transport['address'] ?? '';
            $task['place'] = $transport['place'] ?? '';
            $task['lat'] = $transport['lat'] ?? '';
            $task['lng'] = $transport['lng'] ?? '';
            $task['latlng'] = $transport['latlng'] ?? '';
            $task['province2'] = $transport['province2'] ?? '';
            $task['city2'] = $transport['city2'] ?? '';
            $task['area2'] = $transport['area2'] ?? '';
            $task['address2'] = $transport['address2'] ?? '';
            $task['place2'] = $transport['place2'] ?? '';
            $task['lat2'] = $transport['lat2'] ?? '';
            $task['lng2'] = $transport['lng2'] ?? '';
            $task['latlng2'] = $transport['latlng2'] ?? '';
            $task['transport_type_other'] = $transport['type_other'] ?? '';
            $task['transport_scene_other'] = $transport['scene_other'] ?? '';
        }
        $this->success('ok', $task);
    }


    /**
     * 订单任务列表（地图上的）
     */
    public function taskListInMap()
    {
        // 地图东北角经纬度
        $en_lat = $this->request->post('en_lat', 1000);
        $en_lng = $this->request->post('en_lng', 1000);
        // 地图西南角经纬度
        $ws_lat = $this->request->post('ws_lat', 1000);
        $ws_lng = $this->request->post('ws_lng', 1000);
        // 验证数值有效性
        if(!($en_lat >= -90 && $en_lat <= 90) && ($en_lng >= -180 && $en_lng <= 180)) $this->success('东北角经纬度不正确');
        if(!($ws_lat >= -90 && $ws_lat <= 90) && ($ws_lng >= -180 && $ws_lng <= 180)) $this->success('西南角经纬度不正确');
        // 验证东北角西南角相对位置，不考虑日期变更线
        if ($en_lat < $ws_lat || $en_lng < $ws_lng) $this->success('东北角西南角相对位置不正确');

        $query = TaskModel::where(['is_deleted'=>0, 'status'=>1])->with(['category', 'transport'])
            ->field('id,name,exec_at,place,category_id,lat,lng,task_status')
            ->where('task_status', TaskModel::TASK_STATUS__PENDING_ACCEPTANCE)
            ->whereTime('exec_at', '>', date('Y-m-d H:i:s'));
        // 过滤经纬度数据
        $query->where([
            ['lat', '>=', $ws_lat],
            ['lat', '<=', $en_lat],
            ['lng', '>=', $ws_lng],
            ['lng', '<=', $en_lng],
        ]);
        // 筛选项
        $category_id = $this->request->post('category_id', 0);
        $time_order = $this->request->post('time_order', 'desc');
        $price_order = $this->request->post('price_order', '');
        if (!empty($category_id)) $query->where('category_id', $category_id);
        $order_arr = [];
        if (in_array($time_order, ['desc', 'asc'])) $order_arr[] = 'exec_at '.$time_order;
        if (in_array($price_order, ['desc', 'asc'])) $order_arr[] = 'money '.$price_order;
        $order_arr[] = 'id desc';
        $query->order(join(',', $order_arr));
        $list = get_list($query);
        // 数据清洗
        foreach ($list['list'] as &$vo){
            $vo['exec_at'] = date('Y-m-d H:i', strtotime($vo['exec_at']));
            $vo['category'] = array_keep($vo['category'], ['id', 'name', 'img']);
            $vo['transport_scene'] = $vo['transport']['scene'] ?? '';
        }
        $this->success('ok', $list);
    }
}